package com.sky.Push;

import com.sky.Protocol.MessageProtocol;
import com.sky.Push.Annotion.ObjectMethod;
import com.sky.Push.Singleton;
import com.sky.Util.Constant;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sun on 2017-06-14.
 */
public class RequestHandler extends Singleton {

    public static Map<Integer,ObjectMethod> methodMap = new HashMap<>();

    public void handle(MessageProtocol msg) {
        ObjectMethod om = methodMap.get(msg.getHeader().getMsgType());
        if(om == null) {
            msg.setBody(Constant.NOT_SUPPORT_MSG_TYPE);
            return ;
        }

        Method method = om.getMethod();
        Object obj = om.getObj();
        Class[] clazz = method.getParameterTypes();

        assert clazz.length == 1;

        try {
            String response = null;
            String type = clazz[0].getName();

            if( type.equals( String.class.getName() ) ) {
                response = (String)method.invoke(obj,msg.getBody());
            }
            else if( type.equals( msg.getClass().getName() ) ) {
                response = (String)method.invoke(obj,msg);
            }

            msg.setBody(response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
